﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Pixysoft.Framework.Verifications;
using Pixysoft.Framework.Noebe.Orm.Controller;
using Pixysoft.Tools;
using System.Reflection;

namespace Pixysoft.Framework.Noebe.Orm.Core
{
    class OrmSession : IOrmSession
    {
        INoebeCommand command = null;

        public OrmSession(INoebeCommand command)
        {
            this.command = command;
        }

        public T Create<T>()
        {
            Type type = typeof(T);

            string objectName = ReflectHelper.GetInterfaceTypeName(type);

            string tableName = MappingHelper.GetTableName(objectName);

            string sidName = MappingHelper.GetSysIDName();

            DataTable table = OrmCommandController.GetSchema(tableName);

            DataRow row = table.NewRow();

            row[sidName] = StringHelper.CreatePrimaryKey();

            row[StringHelper.ORM_CREATEDATE] = GlobalTimer.Instance.GetGlobalTime();

            row[StringHelper.ORM_MODIDATE] = GlobalTimer.Instance.GetGlobalTime();

            ObjectProxy proxy = new ObjectProxy(StructStatus.Insert, row);

            return new DynamicOrmProxy<T>(proxy).GetTransparentProxy();
        }

        public virtual int Save(params object[] targets)
        {
            int affectCounter = 0;

            foreach (object target in targets)
            {
                if (target == null)
                    continue;

                ObjectProxy proxy = ConversionController.ObjectToProxy(target);

                //先 插入->修改 自己

                affectCounter += TrySaveObject(proxy, null);

                proxy.GetObjectStruct().Status = StructStatus.Select;

                //然后 删除->插入->修改 建立关系表

                affectCounter += TrySaveValueRelation(proxy, null);

                affectCounter += TrySaveLinkRelation(proxy, null);

            }

            return affectCounter;
        }

        public INoebeCommand GetCommand()
        {
            return command;
        }

        public virtual void SetCommand(INoebeCommand command)
        {
            this.command = command;
        }


        protected int TrySaveObject(ObjectProxy proxy, string groupCode)
        {
            DataRow objectRow = proxy.GetObjectRow();

            switch (proxy.GetObjectStruct().Status)
            {
                case StructStatus.None:
                case StructStatus.Select:
                    return 0;
                case StructStatus.Update:
                    {
                        objectRow[StringHelper.ORM_MODIDATE] = Pixysoft.Tools.GlobalTimer.Instance.GetGlobalTime();

                        objectRow[StringHelper.ORM_GROUPCODE] = groupCode;

                        return command.Update(objectRow);
                    }
                case StructStatus.Insert:
                    {
                        objectRow[StringHelper.ORM_CREATEDATE] = Pixysoft.Tools.GlobalTimer.Instance.GetGlobalTime();

                        objectRow[StringHelper.ORM_MODIDATE] = Pixysoft.Tools.GlobalTimer.Instance.GetGlobalTime();

                        objectRow[StringHelper.ORM_GROUPCODE] = groupCode;

                        return command.Insert(objectRow);
                    }
                default:
                    throw Exceptions.UnexpectedResultException("object status is invalid. status:{0}, object:{1}",
                        proxy.GetObjectStruct().Status, proxy.ObjectName);
            }
        }

        protected int TrySaveValueRelation(ObjectProxy proxy, string groupCode)
        {
            int affectCounter = 0;

            foreach (LinkFromStruct linkFrom in proxy.LinkValueRows.Keys)
            {
                List<LinkValueStruct> links = proxy.LinkValueRows[linkFrom];

                string linkTableName = MappingHelper.GetLinkTableName(linkFrom.ObjectName, linkFrom.FieldName);

                foreach (LinkValueStruct tableStruct in links)
                {
                    switch (tableStruct.LinkStatus)
                    {
                        case LinkStatus.DeleteAll:
                            {
                                affectCounter += OrmCommandController.DeleteValueList(command, linkFrom.ObjectName, linkFrom.FieldName, linkFrom.SidValue);

                                break;
                            }

                        default:
                            break;
                    }
                }

                List<object> insertList = new List<object>();
                List<object> deleteList = new List<object>();

                foreach (LinkValueStruct tableStruct in links)
                {
                    switch (tableStruct.LinkStatus)
                    {
                        case LinkStatus.Insert:
                            {
                                insertList.Add(tableStruct.Value);

                                break;
                            }

                        case LinkStatus.Delete:
                            {
                                deleteList.Add(tableStruct.Value);

                                break;
                            }

                        default:
                            continue;
                    }
                }

                if (deleteList.Count > 0)
                {
                    affectCounter += OrmCommandController.RemoveFromValueList(command, linkFrom.ObjectName, linkFrom.FieldName, linkFrom.SidValue, deleteList);
                }

                if (insertList.Count > 0)
                {
                    DataTable linkToTable = OrmCommandController.CreateLinkValueTable(linkFrom.ObjectName, linkFrom.FieldName, linkFrom.SidValue, insertList, groupCode);
                    affectCounter += command.Insert(linkToTable);
                }
            }

            proxy.LinkValueRows.Clear();//clear buffer

            return affectCounter;
        }

        protected int TrySaveLinkRelation(ObjectProxy proxy, string groupCode)
        {
            int affectCounter = 0;

            foreach (LinkFromStruct linkFrom in proxy.LinkToRows.Keys)
            {
                //DELETE ALL

                foreach (LinkToStruct tableStruct in proxy.LinkToRows[linkFrom])
                {
                    switch (tableStruct.Status)
                    {
                        case LinkStatus.DeleteAll:
                            {
                                affectCounter += OrmCommandController.DeleteList(
                                    command, linkFrom.ObjectName, linkFrom.FieldName, linkFrom.SidValue);

                                break;
                            }
                        default:
                            break;
                    }
                }


                List<Int64> deleteList = new List<Int64>();
                List<Int64> insertList = new List<Int64>();

                //DELETE/INSERT

                foreach (LinkToStruct tableStruct in proxy.LinkToRows[linkFrom])
                {
                    switch (tableStruct.Status)
                    {
                        case LinkStatus.Insert:
                            {
                                insertList.Add(tableStruct.SidValue);
                                break;
                            }

                        case LinkStatus.Delete:
                            {
                                deleteList.Add(tableStruct.SidValue);
                                break;
                            }

                        default:
                            continue;
                    }
                }

                if (deleteList.Count > 0)
                {
                    affectCounter += OrmCommandController.RemoveFromList(command, linkFrom.ObjectName, linkFrom.FieldName, linkFrom.SidValue, deleteList);
                }

                if (insertList.Count > 0)
                {
                    DataTable linkToTable = OrmCommandController.CreateLinkToTable(linkFrom.ObjectName, linkFrom.FieldName, linkFrom.SidValue, insertList, groupCode);

                    affectCounter += command.Insert(linkToTable);
                }
            }

            //re construct

            proxy.LinkToRows.Clear();//clear buffer

            return affectCounter;
        }


        public int Delete(params object[] targets)
        {
            int affectCounter = 0;

            //先 删除链接表

            //再 删除对象

            foreach (object target in targets)
            {
                if (target == null)
                    continue;

                ObjectProxy proxy = ConversionController.ObjectToProxy(target);

                affectCounter += TryDeleteRelation(target.GetType(), proxy);

                affectCounter += TryDeleteObject(proxy);
            }

            return affectCounter;
        }

        private int TryDeleteObject(ObjectProxy proxy)
        {
            return OrmCommandController.DeleteObject(command, proxy.ObjectName, proxy.SidValue);
        }

        private int TryDeleteRelation(Type targetType, ObjectProxy proxy)
        {
            int affectCounter = 0;

            foreach (PropertyInfo property in targetType.GetProperties())
            {
                if (!property.CanRead)
                    continue;

                switch (ReflectHelper.GetOrmTypeByType(property.PropertyType))
                {
                    case DotNetPropertyType.InterfaceList:
                    case DotNetPropertyType.ObjectList:
                    case DotNetPropertyType.InterfaceArray:
                    case DotNetPropertyType.ObjectArray:
                        {
                            affectCounter += OrmCommandController.DeleteList(command, proxy.ObjectName, property.Name, proxy.SidValue);
                            break;
                        }
                    case DotNetPropertyType.ValueArray:
                    case DotNetPropertyType.ValueList:
                        {
                            affectCounter += OrmCommandController.DeleteValueList(command, proxy.ObjectName, property.Name, proxy.SidValue);
                            break;
                        }
                    default:
                        {
                            break;
                        }
                }
            }

            return affectCounter;
        }

    }
}
